package org.nicocube.airain.common.client.form;

import org.nicocube.airain.domain.client.util.Publisher;
import org.nicocube.airain.domain.client.util.Subscriber;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.Constants;
import com.google.gwt.user.client.ui.HasValue;
import com.google.gwt.user.client.ui.Widget;

public abstract class FormField<I> implements NamedWidgetProvider,Subscriber {
	protected final String name;
	private final Form form;
	private HasValue<I> widget;

	public FormField(String name, Form form, Constants constants) {
		this.name = name;
		this.form = form;
		buildWidget(constants);
	}

	public String getName() {
		return name;
	}

	void buildWidget(Constants constants) {
		widget = constructWidget(constants);
		if (getInForm()!=null) widget.setValue(getInForm());
		widget.addValueChangeHandler(new ValueChangeHandler<I>() {
			@Override
			public void onValueChange(ValueChangeEvent<I> event) {
				setInForm(event.getValue());
			}

		});
		
		form.subscribe(this);
	}

	protected abstract void setInForm(I value);
	protected abstract I getInForm();

	protected abstract HasValue<I> constructWidget(Constants constants);

	public Widget getWidget() {
		return (Widget) widget;
	}

	@Override
	public void update(Publisher publisher) {
		widget.setValue(getInForm());
	}

}